package com.baitiaojun.common.utils.captcha;

import com.baitiaojun.common.enums.impl.ServerExpEnums;
import com.baitiaojun.common.exception.ServerException;
import com.baitiaojun.common.utils.io.IoUtils;
import com.baitiaojun.common.utils.servlet.ServletUtils;
import com.baitiaojun.common.utils.spring.SpringUtils;
import com.baitiaojun.common.utils.string.StringUtils;
import com.google.code.kaptcha.impl.DefaultKaptcha;

import javax.servlet.http.HttpServletResponse;

/**
 * 图形验证码工具类
 */
public class CaptchaUtils {

    /**
     * 生成指定文本
     * @param text
     */
    public static void printCaptcha(String text) {
        createCaptcha(text);
    }

    /**
     * 生成默认文本
     */
    public static void printCaptcha() {
        createCaptcha(null);
    }

    public static void createCaptcha(String text) {
        HttpServletResponse response = ServletUtils.getResponse();
        if (response == null) {
            throw new ServerException(ServerExpEnums.EXP_INSTANCE_RESPONSE);
        }
        setDefaultHeader(response);
        DefaultKaptcha kaptchaBean = SpringUtils.getBean("captchaProducer", DefaultKaptcha.class);
        assert kaptchaBean != null;
        if (StringUtils.isEmpty(text)) {
            text = kaptchaBean.createText();
        }
        IoUtils.writeImage(response, kaptchaBean.createImage(text));
    }

    public static void setDefaultHeader(HttpServletResponse response) {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
    }
}
